package com.lv.suyiyong.hfrbusines.ui

import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.view.View
import android.view.View.OnClickListener
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ScreenUtils
import com.blankj.utilcode.util.SizeUtils
import com.lv.common.base.BaseActivity
import com.lv.common.imp.OnPositionTListener
import com.lv.common.imp.OnPositionTMore
import com.lv.common.ktx.initSingleClickListener
import com.lv.common.network.model.DataResult
import com.lv.common.utils.ARoutUtils
import com.lv.common.utils.AnimationUtils
import com.lv.common.utils.Constants
import com.lv.common.utils.DensityUtil
import com.lv.common.utils.StatusBarUtil
import com.lv.common.utils.YgxUtilsKt
import com.lv.common.utils.showToast
import com.lv.common.widget.recyclerview.decoration.SpacesItemDecoration
import com.lv.service.bean.ClientItemBean
import com.lv.service.bean.CommonSelectedBean
import com.lv.service.dialog.Recycler2SelectedMorePopupView
import com.lv.service.dialog.RecyclerSelectedTagTopHBottom52PopupView
import com.lv.service.model.ServiceViewModel
import com.lv.service.network.BaseYgxRsp
import com.lv.service.network.onBizError
import com.lv.service.network.onBizOK
import com.lv.service.network.onFailure
import com.lv.service.network.onSuccess
import com.lv.service.room.address.LocationNewReceiptAddressDbHelper
import com.lv.service.room.address.ReceiptAddressItem
import com.lv.service.weidget.picker.ListSingleTextPopupView
import com.lv.suyiyong.hfrbusines.R
import com.lv.suyiyong.hfrbusines.adapter.ClientsHFRAdapter
import com.lv.suyiyong.hfrbusines.databinding.ActivityHfrClientsBinding
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.lxj.xpopup.enums.PopupPosition
import com.lxj.xpopup.interfaces.XPopupCallback
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.withContext
import org.koin.androidx.viewmodel.ext.android.viewModel

/**
 * 作者： ygx
 * 创建日期：2025/7/5 下午4:16
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 *
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：亨富然开户
 */
@Route(path = ARoutUtils.ClientsHFRActivity)
class ClientsHFRActivity : BaseActivity<ActivityHfrClientsBinding>(),
    OnClickListener {

//    @Autowired(name = "cpyid")
//    @JvmField
//    var mCpyid: String = ""

    private val mStatusBeans = mutableListOf<CommonSelectedBean>()
    private val mAddressBeans = mutableListOf<CommonSelectedBean>()
    private val mTypeTopBeans = mutableListOf<CommonSelectedBean>()
    private val mTypeBottomBeans = mutableListOf<CommonSelectedBean>()
    private var mStart = "0"
    private var mSalseStatus = "0"
    private var mEnd = "${System.currentTimeMillis()}"
    private val mParamsMap = mutableMapOf<String, String>()
    private val mBeans = mutableListOf<ClientItemBean>()
    private var mAdapter: ClientsHFRAdapter? = null
    private var page: Int = 1
    private var pageSize: Int = Constants.pageSize
    private var UPDATED: Long = System.currentTimeMillis()
    private val viewModel: ServiceViewModel by viewModel()
    private val myScope: CoroutineScope = CoroutineScope(SupervisorJob())

    override fun getLayoutRes() = R.layout.activity_hfr_clients
    override fun initView() {
        super.initView()
        initStatusBar(this, true, true)
        ARouter.getInstance().inject(this)
        mBinding.apply {
            StatusBarUtil.setHeightAndPadding(this@ClientsHFRActivity, titleBar)
            titleBar.setTitle("客户列表")
            titleBar.setTitleIv(com.lv.common.R.drawable.logo_hfr_small)
            titleBar.onClickBackIcon { finish() }
            initSingleClickListener(tvOpen, llSaler, llArea, llStatus, viewSearch)
        }
    }

//    fun getCompanyCypid(): String? {
//        return mCpyid
//    }


    override fun initConfig() {
        super.initConfig()

//        mParamsMap["cpyid"] = mCpyid
        showLoadErrorView("加载中……", showBack = true) {
            finish()
        }
        lifecycleScope.launchWhenCreated {
            val taskAddress = async {
                val mAllAddress = getAddressForDB()
                mAddressBeans.clear()
                mAddressBeans.add(CommonSelectedBean("全部地区", "", true))
                mAllAddress?.forEach { addressItem ->
                    mAddressBeans.add(CommonSelectedBean(addressItem.name))
                }
            }
//            val taskFindhengPros = async {
//                val result = findhengPros()
//                parsefindhengProsResult(result)
//            }


            taskAddress.await()
//            taskFindhengPros.await()

            initPage()
        }
    }

    private suspend fun findhengPros(): DataResult<BaseYgxRsp> {
        return withContext(Dispatchers.IO) {
            myScope.async {
                viewModel.findhengPros(mParamsMap)
            }.await()
        }
    }

    private fun parsefindhengProsResult(data: DataResult<BaseYgxRsp>) {
//        loadFinished()
        data.onSuccess {
            onBizOK<Any> { code, data, message, result ->

            }
            onBizError<Any> { code, message, data ->
//                showToast(message)
            }
        }
        data.onFailure {

        }
    }

    private fun initPage() {
        loadFinished()
        initAdapter()
        mStatusBeans.clear()
        mStatusBeans.add(CommonSelectedBean("全部状态", "", true))
        mStatusBeans.add(CommonSelectedBean("已上线", "1", false))
        mStatusBeans.add(CommonSelectedBean("已下线", "2", false))

        mTypeTopBeans.clear()
        mTypeTopBeans.add(CommonSelectedBean("金牌", "2"))
        mTypeTopBeans.add(CommonSelectedBean("认证", "1"))
        mTypeTopBeans.add(CommonSelectedBean("普通", "0"))
        mTypeBottomBeans.clear()
        mTypeBottomBeans.add(CommonSelectedBean("工厂店", "0"))
        mTypeBottomBeans.add(CommonSelectedBean("品牌店", "1"))

    }

    private suspend fun getAddressForDB(): List<ReceiptAddressItem>? {
        return withContext(Dispatchers.IO) {
            //所有城市
            LocationNewReceiptAddressDbHelper.getAllLocationSuspend(this@ClientsHFRActivity)
        }
    }


    private var mBpro = ""
    private fun initAdapter() {
        mBinding.rvContent.setHasFixedSize(true)
        mAdapter = ClientsHFRAdapter(mAddressBeans)
        mBinding.rvContent.adapter = mAdapter
        mBinding.rvContent.addItemDecoration(
            SpacesItemDecoration(
                SizeUtils.dp2px(10.0f), SizeUtils.dp2px(10.0f), false
            )
        )
        mAdapter?.setEmptyView(getEmptyCenterView(mBinding.rvContent, "暂无内容"))
        mAdapter?.onViewJJClickListener = OnPositionTListener { position, data ->
            showToast("进件资料")
        }
        mAdapter?.onViewDJClickListener = OnPositionTListener { position, data ->
            showDJManagerPopView()
        }
        mAdapter?.onViewTelClickListener = OnPositionTListener { position, data ->
            val tels = mutableListOf<String>()
            tels.add(Constants.DMXS_TEL_BOSS)
            showPhonsDialog(tels)
        }
//        UserDbHelper.getLiveUserInfo(this).observeKt {
//            mBpro = it?.getBpro() ?: ""
//            paramsMap["province"] = mBpro
//            findMyCustomer()
//        }

    }

//    private fun findPayCompanyList() {
//        mParamsMap["start"] = mStart
//        mParamsMap["end"] = mEnd
//        startLoading()
//        lifecycleScope.launchWhenCreated {
//            val result: DataResult<BaseYgxRsp> =
//                myScope.async {
//                    viewModel.findPayCompanyList(
//                        page, pageSize, UPDATED, mParamsMap
//                    )
//                }
//                    .await()
//            parsefindPayCompanyListResult(result)
//        }
//    }
//
//    private fun parsefindPayCompanyListResult(data: DataResult<BaseYgxRsp>) {
//        loadFinished()
//        data.onSuccess {
//            onBizOK<ClientPageDataBean> { code, data, message, result ->
//                val items = data?.items
//                if (!items.isNullOrEmpty()) {
//                    UPDATED = items[items.size - 1].updated ?: 0
//                }
//                MyUtils.recyclerviewSetData(
//                    page, pageSize, mBinding.refresh, mBeans, items, mAdapter
//                )
//            }
//            onBizError<Any> { code, message, data ->
//                mBinding.refresh.finishRefresh()
//                mBinding.refresh.finishLoadMore()
//                showToast(message)
//            }
//        }
//        data.onFailure {
//            mBinding.refresh.finishRefresh()
//            mBinding.refresh.finishLoadMore()
//        }
//    }

    override fun initEvents() {
        super.initEvents()

        mBinding.refresh.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                page = 1
                UPDATED = System.currentTimeMillis()

//                findPayCompanyList()
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                page++
//                findPayCompanyList()
            }
        })

        rigestEventBus()
    }

    private fun showPhonsDialog(tels: List<String>?) {
        if (tels.isNullOrEmpty()) {
            return
        }
        if (tels.size == 1) {
            val phone = tels[0]
            YgxUtilsKt.callAllPhone(this@ClientsHFRActivity, phone)
        } else {
            val phons = mutableListOf<CommonSelectedBean>()
            for (i in tels) {
                phons.add(CommonSelectedBean(i))
            }
            val popupView = ListSingleTextPopupView(
                this@ClientsHFRActivity,
                phons
            ) { position, data ->
                if (position != -1) {
                    YgxUtilsKt.callAllPhone(this@ClientsHFRActivity, data?.name ?: "")
                }
            }
            XPopup.Builder(this)
                .isViewMode(true)
                .popupPosition(PopupPosition.Bottom)
                .asCustom(popupView)
                .show()
        }
    }

    private fun rigestEventBus() {

    }

//    private var mHintDialog: HintDialog? = null
//    private fun showHintDialog(data: ClientItemBean?) {
//        mHintDialog = HintDialog(this, "提示", "添加到我的客户列表", true, true, {
//            addCustomer(data)
//        })
//        mHintDialog?.show()
//    }


    override fun initData() {
        super.initData()
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.view_search -> {
                ARouter.getInstance().build(ARoutUtils.ClientSearchActivity)
                    .withString("bpro", mBpro)
                    .navigation()
            }

            R.id.ll_saler -> {//销售额
                when (mSalseStatus) {
                    "0" -> {
                        mSalseStatus = "1"
                        mBinding.ivSaler.setImageResource(com.lv.common.R.drawable.icon_arrow_down_light)
                    }

                    else -> {
                        mSalseStatus = "0"
                        mBinding.ivSaler.setImageResource(com.lv.common.R.drawable.icon_arrow_up_light)
                    }
                }
            }

            R.id.ll_area -> {//地区
                showAddressPop()
            }

            R.id.ll_status -> {//状态
                showStatusPop()
            }

            R.id.tv_open -> {
                ARouter.getInstance().build(ARoutUtils.OpenClientHFRActivity)
                    .navigation()
            }

        }
    }

    private fun showStatusPop() {
//        val topH = StatusBarUtil.getStatusBarHeight(this) + DensityUtil.dip2px(this, 42.0f)
        val topH = ScreenUtils.getScreenHeight() - DensityUtil.dip2px(this, 286.0f)
        val mStatusPop = RecyclerSelectedTagTopHBottom52PopupView(
            this, mStatusBeans, "筛选", topH, com.lv.common.R.drawable.icon_selected_bule, true,
            mPositionTListener = { position, data ->
                val mReson = data.name ?: ""
                mBinding.tvStatus.text = mReson
            }
        )
        XPopup.Builder(this)
            .isViewMode(true)
            .setPopupCallback(object : XPopupCallback {
                override fun onCreated(popupView: BasePopupView?) {

                }

                override fun beforeShow(popupView: BasePopupView?) {
                    AnimationUtils.animationIvOpen(mBinding.ivStatus)
                }

                override fun onShow(popupView: BasePopupView?) {
                }

                override fun onDismiss(popupView: BasePopupView?) {
                }

                override fun beforeDismiss(popupView: BasePopupView?) {
                    AnimationUtils.animationIvClose(mBinding.ivStatus)
                }

                override fun onBackPressed(popupView: BasePopupView?): Boolean {
                    return false
                }

                override fun onKeyBoardStateChanged(popupView: BasePopupView?, height: Int) {
                }

                override fun onDrag(
                    popupView: BasePopupView?,
                    value: Int,
                    percent: Float,
                    upOrLeft: Boolean
                ) {
                }

                override fun onClickOutside(popupView: BasePopupView?) {
                }
            })
            .popupPosition(PopupPosition.Bottom)
            .asCustom(mStatusPop)
            .show()
    }

    private fun showAddressPop() {
        val topH = StatusBarUtil.getStatusBarHeight(this) + DensityUtil.dip2px(this, 42.0f)
        val mAddressPop = RecyclerSelectedTagTopHBottom52PopupView(
            this, mAddressBeans, "筛选", topH, com.lv.common.R.drawable.icon_selected_bule, true,
            mPositionTListener = { position, data ->
                val mReson = data.name ?: ""
                mBinding.tvArea.text = mReson
            }
        )
        XPopup.Builder(this)
            .isViewMode(true)
            .setPopupCallback(object : XPopupCallback {
                override fun onCreated(popupView: BasePopupView?) {

                }

                override fun beforeShow(popupView: BasePopupView?) {
                    AnimationUtils.animationIvOpen(mBinding.ivArea)
//                    val ints = mutableListOf<Int>()
//                    ints.add(0)
//                    ints.add(1)
//                    initDJDatas(0, ints)
                }

                override fun onShow(popupView: BasePopupView?) {
                }

                override fun onDismiss(popupView: BasePopupView?) {
                }

                override fun beforeDismiss(popupView: BasePopupView?) {
                    AnimationUtils.animationIvClose(mBinding.ivArea)
                }

                override fun onBackPressed(popupView: BasePopupView?): Boolean {
                    return false
                }

                override fun onKeyBoardStateChanged(popupView: BasePopupView?, height: Int) {
                }

                override fun onDrag(
                    popupView: BasePopupView?,
                    value: Int,
                    percent: Float,
                    upOrLeft: Boolean
                ) {
                }

                override fun onClickOutside(popupView: BasePopupView?) {
                }
            })
            .popupPosition(PopupPosition.Bottom)
            .asCustom(mAddressPop)
            .show()
    }

    private fun showDJManagerPopView() {
        val topH = ScreenUtils.getScreenHeight() - SizeUtils.dp2px(482.0f)
        val popupView = Recycler2SelectedMorePopupView(
            this, "等级管理", mTypeTopBeans, mTypeBottomBeans, topH, true,
            false, mSelectedTag = com.lv.common.R.drawable.bg_f1f7ff_20,
            mSelectedColor = Color.parseColor("#026DFF"),
            mPositionMListener = object : OnPositionTMore<List<CommonSelectedBean>> {
                override fun onClick(position: Int, vararg data: List<CommonSelectedBean>?) {
                    mTypeTopBeans.clear()
                    mTypeBottomBeans.clear()
                    val topSelectedBeans = data[0]
                    val bottomSelectedBeans = data[1]
                    topSelectedBeans?.let { mTypeTopBeans.addAll(it) }
                    bottomSelectedBeans?.let { mTypeBottomBeans.addAll(it) }
//                    val list = mTypeBeans.filter { it.selected }.map { it.name }
//                        .joinToString(separator = "")
//                    val listBottom = mTypeBottomBeans.filter { it.selected }.map { it.name }
//                        .joinToString(separator = "")
//                    mSpecially = mTypeBeans.filter { it.selected }.map { it.tag }
//                        .joinToString(separator = "_")
//                    mStyle = mTypeBottomBeans.filter { it.selected }.map { it.tag }
//                        .joinToString(separator = "_")
//
//                    var text = "${list}-$listBottom"
//                    if (text == "全部-全部") {
//                        text = "全部"
//                    }
//                    if (text.startsWith("-")) {
//                        text = text.drop(1)
//                    }
//                    if (text.endsWith("-")) {
//                        text = text.dropLast(1)
//                    }
//                    if (text.isEmpty()) {
//                        text = "全部"
//                    }
//                    mBinding?.tvTime?.text = text
//                    // isspecially 0 普通  style
//                    mParamsMap["isspecially"] = mSpecially//0 全部 1 认证 2金牌
//                    mParamsMap["style"] = mStyle//
//                    findCouponStatistics()
                }
            })
        XPopup.Builder(this)
            .isViewMode(true)
            .popupPosition(PopupPosition.Bottom)
            .asCustom(popupView)
            .show()
        popupView.setTitleTop("店铺等级")
            .setTitleBottom("店铺类型（可多选）")
            .setBottomBg(com.lv.common.R.drawable.bg_theme_20)
    }

    private fun initDJDatas(firstSelectedPosition: Int, secoundSelectedPosition: MutableList<Int>) {
        mTypeTopBeans.forEach { it.selected = false }
        if (firstSelectedPosition >= 0 && firstSelectedPosition < mTypeTopBeans.size) {
            mTypeTopBeans[firstSelectedPosition].selected = true
        }

        mTypeBottomBeans.forEach { it.selected = false }
        secoundSelectedPosition.forEach {
            if (it >= 0 && it < mTypeBottomBeans.size) {
                mTypeBottomBeans[it].selected = true
            }
        }


    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (data == null) {
            return
        }
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
//                1 -> {
//                    val name = data.getStringExtra("content")
//                    if (!name.isNullOrEmpty() && name != mCompany?.name) {
//                        setCompanyName(name, 0)
//                    }
//                }


            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
//        if (mHintDialog?.isShowing == true) {
//            mHintDialog?.dismiss()
//        }
    }
}